package com.example.demo.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class CosUtil {

    private final static String secretId = "AKID015Kb4UqFg3HxZAqXMF6z7FGFYtXl8Vg";
    private final static String secretKey = "9KQh5Sju2EQczgVOGykiE8Of1KdutTAu";
    private final static String regionName = "ap-guangzhou";
    private final static String bucketName = "cc-1322096065";

    public static String uploadResource(MultipartFile file ,String path) throws IOException {
        COSCredentials cosCredentials = new BasicCOSCredentials(secretId,secretKey);
        ClientConfig clientConfig = new ClientConfig( new Region(regionName));

        COSClient client = new COSClient(cosCredentials,clientConfig);

        InputStream inputStream = file.getInputStream();

        ObjectMetadata objectMetadata = new ObjectMetadata();

        objectMetadata.setContentLength(file.getSize());

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,path,inputStream,objectMetadata);
        client.putObject(putObjectRequest);
        URL objectUrl = client.getObjectUrl(bucketName, path);
        return objectUrl.toString();
    }
}
